<template>
  <div class="inout-box">
    <el-dialog width="600px" title="导入" v-model="dialogFormVisible" :close-on-click-modal="false" :draggable="true"
      @close="dialogClose">
      <div class="content-box">
        <el-tabs v-model="activeName" @tab-change="tabChange">
          <el-tab-pane v-if="activeName == 1" label="非在网订单导入" :name="1">
            <!-- <el-alert title="订单导入后如果销售渠道和外部订单号都真实存在，则会默认同步到电商平台发货，如果导入订单不想同步发货请修改销售渠道或外部单号" type="success" :closable="false" /> -->
            <div class="content-item">
              <p>
                1、先下载导入模版，根据模版提示填写好内容后再上传
              </p>
              <el-button style="margin-top:20px;" @click="templateDownLoad">下载模板</el-button>
            </div>
            <div class="content-item">
              <p>
                2、上传填写好后的文件，文件格式xls、xlsx格式的文件
              </p>
              <div class="upload-box">
                <el-button @click="uploadHandle">选择上传的文件</el-button>
                <input ref="uploadInputRef" style="display:none" type="file"
                  accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                  @change="uploadChange">
                <div v-show="fileForm.file" class="upload-file">
                  <span>{{ fileForm.fileName }}</span>
                  <el-icon class="delete-btn" @click="deleteFile">
                    <Close />
                  </el-icon>
                </div>
              </div>
            </div>
            <div v-show="errmsg" style="color:#f56c6c;">{{ errmsg }}</div>
          </el-tab-pane>
          <el-tab-pane v-if="activeName == 2" label="批量同步状态" :name="2">
            <!-- <el-alert title="订单导入后如果销售渠道和外部订单号都真实存在，则会默认同步到电商平台发货，如果导入订单不想同步发货请修改销售渠道或外部单号" type="success" :closable="false" /> -->
            <div class="content-item">
              <p>
                1、先下载导入模版，根据模版提示填写好内容后再上传
              </p>
              <el-button style="margin-top:20px;" @click="templateDownLoad">下载模板</el-button>
            </div>
            <div class="content-item">
              <p>
                2、上传填写好后的文件，文件格式xls、xlsx格式的文件
              </p>
              <div class="upload-box">
                <el-button @click="uploadHandle">选择上传的文件</el-button>
                <input ref="uploadInputRef" style="display:none" type="file"
                  accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                  @change="uploadChange">
                <div v-show="fileForm.file" class="upload-file">
                  <span>{{ fileForm.fileName }}</span>
                  <el-icon class="delete-btn" @click="deleteFile">
                    <Close />
                  </el-icon>
                </div>
              </div>
            </div>
            <div v-show="errmsg" style="color:#f56c6c;">{{ errmsg }}</div>
          </el-tab-pane>
          <!-- <el-tab-pane label="各平台订单快捷导入" :name="2">
          </el-tab-pane>
          <el-tab-pane label="导出及修改我的订单" :name="3">
          </el-tab-pane> -->
          <!-- <el-tab-pane label="导出区域列表" :name="3">
            <div class="content-item">
              <div class="upload-box" style="border:none;background:none;">
                <el-button @click="outArea">导出区域列表</el-button>
              </div>
            </div>
          </el-tab-pane> -->
        </el-tabs>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <div style="margin-left: auto;">
            <el-button @click="dialogFormVisible = false">关闭</el-button>
            <el-button type="primary" @click="submitHandle">
              上传
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reactive, ref, toRefs, watch } from 'vue'
import { BlobDownLoad, successDeal, warningDeal, getStore } from '@/utils/utils'
import api from '../api'
import { useStateStore } from '@/store'
import axios from "axios"
export default {
  setup(props, context) {
    const store = useStateStore()

    const uploadInputRef = ref(null)
    const importHisRef = ref(null)

    const state = reactive({
      activeName: 1,
      dialogFormVisible: false,
      fileForm: {},
      errmsg: null,
    })

    watch(() => state.fileForm, (newVal, oldVal) => {
      if (newVal.file) {
        state.errmsg = null
      } else {
        state.errmsg = '请选择上传文件'
      }
    })

    function dialogShow(activeName) {
      state.activeName = activeName
      state.errmsg = null
      state.dialogFormVisible = true
    }

    function tabChange(e) {
      //tabs改变
    }

    function dialogClose() {
      //弹窗关闭
      deleteFile()
    }

    function templateDownLoad() {
      let apiName = (state.activeName == 1) ? 'offlineTemplete' : 'refreshTemplete'
      api[apiName]({ responseType: "blob" }).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
      }).catch(err => {
        console.log(err)
      })
    }

    function uploadHandle() {
      uploadInputRef.value.click()
    }

    //上传文件
    function uploadChange(e) {
      const myArr = e.target.files[0].name.split('.')
      if (myArr[myArr.length - 1] != 'xls' && myArr[myArr.length - 1] != 'xlsx') {
        state.errmsg = '请上传xls、xlsx格式的文件'
        return
      }
      state.fileForm = {}
      state.fileForm.file = e.target.files[0]
      state.fileForm.fileName = e.target.files[0].name
      uploadInputRef.value.value = ''
    }

    async function uploadFile() {
      const token = window.localStorage.getItem("USER_TOKEN_INRE") || '';
      const uesrInfo = getStore("USER_INFO_INRE") || {};
      const Authorization = getStore("USER_AUTHOR_INRE") || {
        Authorization: `'','','',3,20,''`,
      };
      let param = new FormData()
      param.append('file', state.fileForm.file, state.fileForm.fileName)
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          token: token ? `Bearer ${token}` : '',
          username: uesrInfo.username || '',
          Authorization: Authorization.Authorization,
          platformHeadType: store.getPlatformHeadType,
        }
      }
      let postUrl = (state.activeName == 1) ? '/eas/manage/order/offline/upload' : '/eas/manage/order/active/status/refresh/upload'
      await axios.post(postUrl, param, config).then(res => {
        if (res.data.code == '200') {
          successDeal('文件上传成功!')
          context.emit('dialogClose', true)
          state.dialogFormVisible = false
        } else {
          warningDeal(res.data.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function deleteFile() {
      state.fileForm = {}
    }

    function submitHandle() {
      if (state.fileForm && state.fileForm.file) {
        uploadFile()
      } else {
        state.fileForm = {}
      }
    }

    function outArea() {
      api.areaDown({ responseType: "blob" }).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
      }).catch(err => {
        console.log(err)
      })
    }

    return {
      ...toRefs(state),
      uploadInputRef,
      dialogShow,
      tabChange,
      dialogClose,
      templateDownLoad,
      uploadHandle,
      uploadChange,
      deleteFile,
      submitHandle,
      outArea,
    }
  }
}
</script>

<style lang="scss" scoped>
.content-box {
  .content-item {
    box-sizing: border-box;
    padding: 20px;
    background-color: #f8f9fa;
    margin-top: 20px;
    .upload-box {
      width: 100%;
      border: 1px dashed #dcdee0;
      box-sizing: border-box;
      padding: 40px;
      margin-top: 20px;
      text-align: center;
      background-color: #ffffff;
      .upload-file {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 20px;
        font-size: 12px;
        color: #a7a7a7;
        box-sizing: border-box;
        padding: 5px 10px;
        transition: all 0.3s;
        &:hover {
          background-color: rgba($color: #0081ff, $alpha: 0.8);
          color: #ffffff;
        }
        .delete-btn {
          cursor: pointer;
        }
      }
    }
  }
}
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>